import { setToken } from './../util/auth';
import axios, {
  AxiosError,
  AxiosInstance,
  AxiosRequestHeaders,
  AxiosResponse,
  InternalAxiosRequestConfig
} from 'axios'
import { messageC, notificationC, nullC } from '../util/common'
import qs from 'qs'
import { config } from './config'
import errorCode from './errorCode'
const { result_code, base_url, request_timeout } = config
import { useLoginStore } from '@/store'
import router from '@/router'

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: base_url, // api 的 base_url
  timeout: request_timeout, // 请求超时时间
  withCredentials: false // 禁用 Cookie 等信息
})

const CancelToken = axios.CancelToken;
let pending: any = [];
const removePending = (config: any) => {
  for (let p in pending) {
    if (pending[p].url === config.url) {
      pending[p].cancel();
      pending.splice(p, 1);
    }
  }
}

// request拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig & any) => {
    removePending(config);
    if( config.cancelToken && 
      ((config['data'] || {})['_cancel'] || (config['params'] || {})['_cancel'])
    ) {
        config.cancelToken = new CancelToken((c) => {
          pending.push({ cancel: c, url: config.url});
      })
    }

    const loginStore = useLoginStore()
    config.headers['Authorization'] = 'Basic bGFtcF93ZWI6bGFtcF93ZWJfc2VjcmV0';
    config.headers['tenant'] = 'MDAwMA==';
    const token: string = loginStore.token;
    // const token: string = '';
    if(token) {
      config.headers['token'] = 'Bearer ' + token;
    }

    const params = config.params || {}
    const data = config.data || false
    if (
      config.method?.toUpperCase() === 'POST' &&
      (config.headers as AxiosRequestHeaders)['Content-Type'] ===
        'application/x-www-form-urlencoded'
    ) {
      config.data = qs.stringify(data)
    }

    // get参数编码
    if (config.method?.toUpperCase() === 'GET' && params) {
      config.params = {}
      const paramsStr = qs.stringify(params, { allowDots: true })
      if (paramsStr) {
        config.url = config.url + '?' + paramsStr
      }
    }
    return config
  },
  (error: AxiosError) => {
    console.log(error)
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  async (response: AxiosResponse<any>) => {
    return response
  },
  (error: AxiosError) => {
    const loginStore = useLoginStore()
    const { code, status, path, data = {} } = error.response || {}
    if(error['message'] != "canceled") {
      if(data['msg']) {
        messageC(data['msg'], 'error')
      } else {
        messageC(nullC(errorCode[code || status], errorCode['default']), "error")
      }
    }
    if(code == 401 || status == 401) {
      loginStore.setToken('')
      router.replace('/')
    }
    return Promise.reject(error)
  }
)
export { service }
